package com.xzz.directprint.util;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-12-01 11:19
 * @FullNameClass: com.xzz.directprint.util.ImageToPdfPrinter
 * @Description:
 */
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageToPdfPrinter {

    public void convertImageToPdfAndPrint(String imagePath, String pdfPath) throws IOException {
        // 加载图片
        BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
        Image image = bufferedImage.getScaledInstance(bufferedImage.getWidth(null), bufferedImage.getHeight(null), Image.SCALE_SMOOTH);

        // 创建PDF文档
        PDDocument document = new PDDocument();
        PDPage page = new PDPage();
        document.addPage(page);
        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

        // 将图片添加到PDF页面
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(pdImage, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
        contentStream.close();

        // 保存PDF文档
        document.save(pdfPath);
        document.close();

        // 打印PDF文档
        // 这里需要实现具体的打印逻辑，可能需要调用操作系统命令或者API
        // 示例仅展示如何将图片转换为PDF，并未包含打印逻辑
    }

    public static void main(String[] args) {
        ImageToPdfPrinter printer = new ImageToPdfPrinter();
        try {
            printer.convertImageToPdfAndPrint("d:/tuzhi/abc啊.png", "d:/tuzhi/abc啊.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
